package app.foodnote;

import android.R.color;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import app.foodnote.db.FoodNote;
import app.foodnote.db.FoodNotesDataSource;

public class FoodAdd extends Activity implements LocationListener {
	private static final String TAG = "SaveFoods";
	private FoodNotesDataSource datasource;

	
	private EditText name;
	private EditText address;
	private EditText phonenumber;
	private AutoCompleteTextView cities;
	private EditText othernotes;
	private TextView location;
	
	private double log;
	private double lat;
	
	LocationManager locationManager;
	
	private String[] citiesArray = {"An Giang", "Bà Rịa - Vũng Tàu", "Bạc Liêu", "Bắc Giang" , "Bắc Kạn",
			"Bắc Ninh", "Bến Tre", "Bình Dương ","Bình Định", "Bình Phước"," Bình Thuận", 
			"Cà Mau", "Cao Bằng", "Cần Thơ", "Đà Nẵng", "Đắk Lắk", "Đắk Nông", "Đồng Nai", "Đồng Tháp",
			"Điện Biên", "Gia Lai", "Hà Giang", "Hà Nam", "Hà Nội", "Hà Tĩnh", "Hải Dương", "Hải Phòng","Hòa Bình",
			"Hậu Giang", "Hưng Yên", "Khánh Hòa", "Kiên Giang", "Kon Tum", "Lai Châu", "Lạng Sơn",
			"Lào Cai", "Lâm Đồng", "Long An", "Nam Định", "Nghệ An", "Ninh Bình", "Ninh Thuận", "Phú Thọ",
			"Phú Yên", "Quảng Bình", "Quảng Nam", "Quảng Ngãi", "Quảng Ninh", "Quảng Trị", "Sóc Trăng",
			"Sơn La", "Tây Ninh", "Thái Bình", "Thái Nguyên", "Thanh Hóa", "TP. Hồ Chí Minh",
			"Thừa Thiên - Huế", "Tiền Giang", "Trà Vinh", "Tuyên Quang", "Vĩnh Long", "Vĩnh Phúc", "Yên Bái"
			};
	
	String foodId = null;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle("Thêm Món Ăn");
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.form_add);
		
		name = (EditText) findViewById(R.id.EditName);
		address = (EditText) findViewById(R.id.EditAddr1);
		phonenumber = (EditText) findViewById(R.id.EditTel);
		cities = (AutoCompleteTextView) findViewById(R.id.autocomplete_cities);
		othernotes = (EditText) findViewById(R.id.EditNotes);
		location = (TextView) findViewById(R.id.location);
		
		datasource = new FoodNotesDataSource(this);

		ArrayAdapter<String> cities_adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, citiesArray);
		cities.setThreshold(1);
		cities.setAdapter(cities_adapter);

		// Find Current Location
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Location location = locationManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (location != null) {
			Log.d("Location", location.toString());
			this.onLocationChanged(location);
		}
		else {
			showSettingsAlert();
		}
		
		foodId = getIntent().getStringExtra(FoodPlaces.ID_EXTRA);	
		if(foodId != null){
			//Toast.makeText(getApplicationContext(), "Co ID" + foodId, Toast.LENGTH_LONG).show();
			loadFood();
		}
	}

	private void showSettingsAlert() {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
		alertDialog.setIcon(R.drawable.fail);
		alertDialog.setTitle("Cài đặt GPS");
		alertDialog.setMessage("GPS chưa được kích hoạt. Bạn có muốn mở trình cài đặt?");
		
		//On pressing Setting button
		alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
				startActivity(intent);
			}
		});
		// On pressing cancel button
		alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		
		alertDialog.show();
		
	}

	private void loadFood() {
		datasource.openToRead();
		Cursor c = datasource.getFoodNoteById(foodId);
		c.moveToFirst();
		name.setText(datasource.getName(c));
		address.setText(datasource.getAddress(c));
		phonenumber.setText(datasource.getPhoneNumber(c));
		cities.setText(datasource.getCity(c));
		othernotes.setText(datasource.getOtherNote(c));
		location.setText(String.valueOf(datasource.getLongitude(c) + ", "
				+ String.valueOf(datasource.getLatitude(c))
				));
		c.close();
		datasource.close();
	}
	public void  saveFood(){
		if(foodId == null){
			String message = "Thêm món ăn thành công";
			if(!name.getText().toString().isEmpty() && !address.getText().toString().isEmpty()){
				FoodNote foodnote = new FoodNote(name.getText().toString(), address.getText().toString(), 
						phonenumber.getText().toString(), cities.getText().toString(),
						othernotes.getText().toString(), log, lat);
				datasource.openToWrite();
				datasource.addFoodNotes(foodnote);
				datasource.close();
				
				Toast.makeText(this, message, Toast.LENGTH_LONG).show();
				Log.w(TAG, "Luu thanh cong!");
			}
		} else {
			String message = "Cập nhật món ăn thành công";
			FoodNote foodnote = new FoodNote(name.getText().toString(), address.getText().toString(),
					phonenumber.getText().toString(), cities.getText().toString(),
					othernotes.getText().toString());
			datasource.openToWrite();
			datasource.updateFoodNote(foodId, foodnote);
			datasource.close();
			Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
		}
	}
	@Override
	protected void onResume() {
		super.onResume();
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this); 
		datasource.openToRead();
	}

	@Override
	protected void onPause() {
		saveFood();
		super.onPause();
	}
	@Override
	protected void onDestroy(){
		super.onDestroy();
		datasource.close();
	}
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.form_add_option, menu);
		return true;
	}
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (foodId==null) {
			menu.findItem(R.id.location).setEnabled(false);
		}
		return(super.onPrepareOptionsMenu(menu));
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.location){
			FoodNote foodNote = new FoodNote(lat, log);
			datasource.openToWrite();
			datasource.updateLocation(foodId, foodNote);
			datasource.close();
			Toast.makeText(getApplicationContext(), "Đã lưu địa điểm", Toast.LENGTH_LONG).show();
			Intent foodplace = new Intent(FoodAdd.this, FoodPlaces.class);
			startActivity(foodplace);
		}
		return super.onOptionsItemSelected(item);
	}

	public void onLocationChanged(Location locat) {
		lat = locat.getLatitude();
		log = locat.getLongitude();
		location.setText(String.valueOf(locat.getLatitude()) + ", " + String.valueOf(locat.getLongitude()));
		
	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}

}
